| Conditions | 13 |
| Total Lines | 43 |
| Code Lines | 26 |
| Lines | 0 |
| Ratio | 0 % |
| Changes | 0 | ||
Complex classes like index.js ➔ isPrime often do a lot of different things. To break such a class down, we need to identify a cohesive component within that class. A common approach to find such a component is to look for fields/methods that share the same prefixes, or suffixes.
Once you have determined the fields that belong together, you can apply the Extract Class refactoring. If the component makes sense as a sub-class, Extract Subclass is also a candidate, and is often faster.
| 1 | /** |
||
| 8 | function isPrime(n, k = 100) { |
||
| 9 | if (n === 2 || n === 3) { return true } |
||
| 10 | |||
| 11 | const smallPrimes = [2, 3, 5, 7, 11, 13, 17] |
||
| 12 | |||
| 13 | const res = smallPrimes.map(x => n % x === 0).filter(x => x).includes(true) |
||
| 14 | if (res) return false |
||
| 15 | |||
| 16 | if ( |
||
| 17 | n % 2 === 0 || n % 3 === 0 || n % 5 === 0 || n % 7 === 0 || n < 2) { |
||
| 18 | return false |
||
| 19 | } |
||
| 20 | |||
| 21 | // Write (n - 1) as 2^s * d |
||
| 22 | let s = 0 |
||
| 23 | let d = n - 1 |
||
| 24 | while (d % 2 === 0) { |
||
| 25 | d /= 2 |
||
| 26 | ++s |
||
| 27 | } |
||
| 28 | |||
| 29 | const witness = n => { |
||
| 30 | return Math.floor(Math.random() * (n - 2)) + 2 |
||
| 31 | } |
||
| 32 | |||
| 33 | while (k--) { |
||
| 34 | let a = Math.pow(witness(n), s) |
||
| 35 | |||
| 36 | if (a % n === 1) continue |
||
| 37 | |||
| 38 | let testFails = false |
||
| 39 | for (let i = 0; i < s; i++) { |
||
| 40 | a = Math.pow(a, 2) % n |
||
| 41 | if (a === n - 1) { |
||
| 42 | testFails = true |
||
| 43 | break |
||
| 44 | } |
||
| 45 | } |
||
| 46 | |||
| 47 | if (testFails) return false |
||
| 48 | } |
||
| 49 | return true |
||
| 50 | } |
||
| 51 | |||
| 53 |